import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService service = Executors.newCachedThreadPool();
        while(true){
            //1.从操作系统内核中取出已经建立好的TCP连接
            //  每次新建一个网卡，不关闭会造成文件资源的泄露
            Socket clientSocket = serverSocket.accept();
            //2.处理数据
            //  可以采用多线程的方式来进行处理，实现并发，给多个客户端提供服务
            //  可以使用线程池，避免线程的频繁创建和销毁的开销
            /*Thread t = new Thread(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();*/
            service.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    public void processConnection(Socket clientSocket){
        System.out.printf("[%s:%d]客户端上线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scanner = new Scanner(inputStream);
            while(true){
                if (!scanner.hasNext()){
                    //客户端下线
                    System.out.printf("[%s %d]客户端下线！\n",clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //1.等待读取用户数据
                String request = scanner.next();
                //2.根据用户请求，计算响应
                String response = process(request);
                //3.发送响应
                printWriter.println(response);
                printWriter.flush();
                //4.打印交互信息
                System.out.printf("[%s:%d] req=%s, resp=%s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            //关闭文件资源，防止文件资源泄露
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9999);
        server.start();
    }
}
